package snowflake.zk;

import lombok.extern.log4j.Log4j2;
import org.apache.zookeeper.KeeperException;

import javax.annotation.PostConstruct;
import java.io.IOException;
import java.net.InetAddress;

/**
 * 同一 zk 集群下
 * 服务小于 16 台安全
 * @author dycong
 * @date 2019/7/11 13:17
 */
@Log4j2
public class SequenceUtil {

    private ZkClient zkClient = null;

    private SnowflakeIdWorker snowflakeIdWorker = null;

    private static final String SNOW_FLAKE = "/snowflake";
    private static final String SNOW_FLAKE_WORKER_ID = SNOW_FLAKE + "/workerId";
    private static final String SNOW_FLAKE_DC_ID = SNOW_FLAKE + "/dataCenterId";

    @PostConstruct
    public void init() throws InterruptedException, IOException, KeeperException {
        zkClient = new ZkClient("10.201.7.161:2181", 30000);
        zkClient.createPersistentPath(SNOW_FLAKE, "snowflake-node");
        //机器ID(0-31)
        long workerId = Long.parseLong(getSequence(SNOW_FLAKE_WORKER_ID)) % 32;
        //数据中心ID(0-31)
        long dataCenterId = Long.parseLong(getSequence(SNOW_FLAKE_DC_ID)) % 32;
        snowflakeIdWorker = new SnowflakeIdWorker(workerId, dataCenterId);
        log.info("SequenceUtil init with workerId:{},dataCenterId:{}", workerId, dataCenterId);
    }


    public long nextId() {
        return snowflakeIdWorker.nextId();
    }

    private String getSequence(String path) throws InterruptedException, IOException, KeeperException {
        InetAddress addr = InetAddress.getLocalHost();
        //获得本机IP
        String ip = addr.getHostAddress();
        String node = zkClient.createPath(path, ip);
        return node.substring(path.length());
    }

    public static void main(String[] args) throws InterruptedException, IOException, KeeperException {

        for (int i = 0; i < 10; i++) {
            SequenceUtil sequenceUtil = new SequenceUtil();
            sequenceUtil.init();
        }
    }
}
